package com.ccsoft.broadcastdemo;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


/**
 * 2019年10月6日14:49:51
 * 本项目源码默认是动态注册的方式实现发送广播并且接收广播
 * 如果要修改为静态注册方式将现有代码做如下修改：
 * 1. 注释掉本页面中的 onResume
 * 2. 注释掉本页面中的 onPause
 * 3. 将事件 onClick 下的设置包路径的代码启用
 */
public class MainActivity extends Activity implements View.OnClickListener {
    MyReceiver myReceiver;
    IntentFilter intentFilter;
    EditText etReceivedBroadcast;
    Button btnSendBroadcast;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activit_main);

        etReceivedBroadcast = (EditText) findViewById(R.id.etReceivedBroadcast);
        btnSendBroadcast = (Button) findViewById(R.id.btnSendBroadcast);

        //keep reference to Activity context
        MyApplication myApplication = (MyApplication) this.getApplicationContext();
        myApplication.mainActivity = this;

        btnSendBroadcast.setOnClickListener(this);

        myReceiver = new MyReceiver();
        intentFilter = new IntentFilter("chanchawReceiver");
    }

    // 静态注册方式时要把本方法注释掉
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(myReceiver, intentFilter);

    }

    // 静态注册方式时要把本方法注释掉
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(myReceiver);
    }


    @Override
    public void onClick(View view) {
        Intent intent = new Intent("chanchawReceiver");
        // 使用静态注册时务必去掉下面一行代码的注释，Android 8 更新导致的
//        intent.setPackage("com.ccsoft.broadcastdemo");
        sendBroadcast(intent);
    }
}
